package com.fingard.dsp.bank.directbank.baofoo01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.SplitHelper;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 	宝付对账单下载接口
 */
public class BaoFoo01Statement extends BaoFoo01Base implements IStatement {
	/**
	 * 对账文件下载
	 */
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm)	throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.actNum = p_reqQrySttm.actNum;
		
		retAts.writeStart();
		String respCode = "";
		String respInfo = "";
        OutputStream outStream = null;
        InputStream dataBytes = null;
        ZipFile zip = null;

		try{
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem == null) {
				throw new Exception("未找到账号" + p_reqQrySttm.actNum + "对应的商户配置节点");
			}
			
			Map<String,String> postParams = new HashMap<String,String>();
			
			postParams.put("version", "4.0.0.2");
			postParams.put("member_id", actItem.merchantId);
			postParams.put("file_type", getBankConfig().getValueAsString("bill_type"));
			postParams.put("client_ip", actItem.createIP);
			postParams.put("settle_date", Format.Date10Format.format(p_reqQrySttm.getBusDate()));
			
			// 发送银行
			String[] tmpStrRet = sendToBank("downloadbill", postParams, actItem);
	        
	        // 解析银行返回
	        if(tmpStrRet[0].length() == 0) {
	        	WriteBankLogLn("宝付返回数据: " + tmpStrRet[1]);
	        	
	        	if (tmpStrRet[1].indexOf("resp_code=0000") < 0) {
	        		respCode = "-1";
	        		respInfo = "对账单下载失败";
	        	}
	        	
	        	String[] respStr = tmpStrRet[1].split("&");
	        	
	        	String billData = Base64Decode(respStr[2].split("=")[1]);
	        	
	        	String filename = "D:/"+Format.Date10Format.format(new Date())+".zip";
	        	WriteBankLogLn2("对账单存放路径: " + filename);
	        	
	    		dataBytes = new ByteArrayInputStream(billData.getBytes(getCharset()));//把获取的zip文件的byte放入输入流
	    		File targetFile = new File(filename); 
	    		targetFile.createNewFile(); 
	    		outStream = new FileOutputStream(targetFile);
	    		byte[] by = new byte[1024]; 
	    		while (dataBytes.available() > 0) { 
	    			dataBytes.read(by); //读取接收的文件流
	    			outStream.write(by); //写入文件
	    		} 
	    		StringBuilder content = new StringBuilder();
			    
			    zip = new ZipFile(filename);
				@SuppressWarnings("unchecked")
				Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();  
			      
			    while (entries.hasMoreElements()) {  
			    	ZipEntry ze = entries.nextElement();  
			        Scanner scanner = new Scanner(zip.getInputStream(ze));  
			        while (scanner.hasNextLine()) {  
			             content.append(scanner.nextLine()+"\n");  
			        }  
			        scanner.close();  
			    }  
			    zip.close();  
			      
			    String tmpBillData =  content.toString();// 对账单详细数据
				
	        	if(tmpBillData != null) {
	        		respCode = "0";
	        		respInfo = "";
	        		
	        		// 获取总笔数和总金额
	        		int indexTotalData = tmpBillData.indexOf("商户号|终端号|交易类型|交易子类型|宝付订单号");
					String totalData = tmpBillData.substring(0, indexTotalData);
					
	        		StringReader strreader = new StringReader(totalData);
					BufferedReader tmpreader = new BufferedReader(strreader);
					
					String[] totalColumns = tmpreader.readLine().split("|");
					
					int totalNum = 0;
					while(true){
						String eachline = tmpreader.readLine();
						if(eachline == null){
							break;
						}
						
						String[] totalValues = eachline.split("|");
						if(totalColumns.length == totalValues.length){
							HashMap<String, String> mapTotal = SplitHelper.splitAsValueMap(totalColumns, totalValues);
							
							if(mapTotal.containsKey("总笔数")){
								totalNum += Integer.parseInt(mapTotal.get("总笔数"));
							}
							
							if(mapTotal.containsKey("清算时间")){
								retAts.busDate = mapTotal.get("清算时间").replace("-", "").replace(":", "").replace(" ", "");
							}
						} else {
							break;
						}
					}
					
					retAts.totalNum = String.valueOf(totalNum);
	        		
					String[] line = tmpBillData.split("\n");
					if (line.length > 1) {
						if (tmpBillData.indexOf("商户订单号") > 1) {
							// FI
							int indexFI = tmpBillData.indexOf("商户号|终端号|交易类型|交易子类型|宝付订单号|商户订单号");
							String respFI = tmpBillData.substring(indexFI);
							
							StringReader strReader = new StringReader(respFI);
							BufferedReader tmpReader = new BufferedReader(strReader);
							
							String[] columns = tmpReader.readLine().split("|");
							while(true){
								String eachline = tmpReader.readLine();
								if(eachline == null){
									break;
								}
								String[] values = eachline.split("|");
								if(columns.length == values.length){
									HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
									RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
									
									if(mapKV.containsKey("商户订单号")){
										retDetail.askNumber = mapKV.get("商户订单号");
									}
									
									if(mapKV.containsKey("清算日期")){
										retDetail.busTime = mapKV.get("清算日期").replace("-", "").replace(":", "").replace(" ", "");
									}
									
									if(mapKV.containsKey("交易类型")){
										retDetail.busType = mapKV.get("交易类型");
									}
									
									if(mapKV.containsKey("手续费")){
										retDetail.fee = mapKV.get("手续费");
									}
									
									if(mapKV.containsKey("交易金额")){
										retDetail.amount = mapKV.get("交易金额");
									}
									
									if(mapKV.containsKey("订单状态")){//支付成功/转入退款
										if(mapKV.get("订单状态").equals("1")){
											retDetail.transState = TransState.Success;
										}
										else if(mapKV.get("订单状态").equals("0")){
											retDetail.transState = TransState.ToRefund;
										}
										else{
											retDetail.transState = TransState.Exception;
										}
									}
								}else {
									break;
								}
							 }
						}else {
							// FO
							int indexFO = tmpBillData.indexOf("商户号|终端号|交易类型|交易子类型|宝付订单号|商户代付订单号");
							String respFO = tmpBillData.substring(indexFO);
							
							StringReader strReader = new StringReader(respFO);
							BufferedReader tmpReader = new BufferedReader(strReader);
							
							String[] columns = tmpReader.readLine().split("|");
							while(true){
								String eachline = tmpReader.readLine();
								if(eachline == null){
									break;
								}
								String[] values = eachline.split("|");
								if(columns.length == values.length){
									HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
									RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
									
									if(mapKV.containsKey("商户订单号")){
										retDetail.askNumber = mapKV.get("商户代付订单号");
									}
									
									if(mapKV.containsKey("收款人账号")){
										retDetail.oppAct = mapKV.get("收款人账号");
									}
									
									if(mapKV.containsKey("收款人姓名")){
										retDetail.oppActName = mapKV.get("收款人姓名");
									}
									
									if(mapKV.containsKey("代付订单创建时间")){
										retDetail.postingDate = mapKV.get("代付订单创建时间").replace("-", "").replace(":", "").replace(" ", "");
									}
									
									if(mapKV.containsKey("退款订单创建时间")){
										retDetail.refundSentDate = mapKV.get("退款订单创建时间").replace("-", "").replace(":", "").replace(" ", "");
									}
									
									if(mapKV.containsKey("交易类型")){
										retDetail.busType = mapKV.get("交易类型");
									}
									
									if(mapKV.containsKey("手续费")){
										retDetail.fee = mapKV.get("手续费");
									}
									
									if(mapKV.containsKey("交易金额")){
										retDetail.amount = mapKV.get("交易金额");
									}
									
									if(mapKV.containsKey("订单状态")){//支付成功/转入退款
										if(mapKV.get("订单状态").equals("1")){
											retDetail.transState = TransState.Success;
										}
										else if(mapKV.get("订单状态").equals("0")){
											retDetail.transState = TransState.ToRefund;
										}
										else{
											retDetail.transState = TransState.Exception;
										}
									}
								}else {
									break;
								}
							 }
						}
					}else {
						respCode = "-1";
		        		respInfo = "交易未生成";
					}
	        	}else {
	        		respCode = "-1";
	        		respInfo = tmpStrRet[2].split("=")[1];
	        	}
	        }else{
	        	respCode = "-1";
        		respInfo = tmpStrRet[1];
	        }
	        
	        if (!respCode.equals("0")) {
	        	retAts.writeRespCode(respCode);
	        	retAts.writeRespInfo(respInfo);
	        }
		}catch (Exception e) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo(e.getMessage());
			this.WriteBankLogLn(e);
		} finally {
		    try {
                if (zip != null) {
                    zip.close();
                }
                if (dataBytes != null) {
                    dataBytes.close();
                }
                if (outStream != null) {
                    outStream.flush();
                    outStream.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

		retAts.writeEnd();
		return retAts;
	}
}
